package com.test.threadlocal;

/**
 * @author ：biws
 * @date ：Created in 2020/12/18 16:38
 * @description：加入ThreadLocal之后，线程安全
 */
public class ThreadB extends Thread {
    private int i;
    private SafeThread testThreadLocal;

    ThreadB(int i, SafeThread testThreadLocal) {
        this.i = i;
        this.testThreadLocal = testThreadLocal;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        testThreadLocal.calc();

        System.out.println("i:" + i + ",count:" + testThreadLocal.getCount());
    }
}

class SafeThread {

    private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    private int count = 0;

    public void calc() {
        threadLocal.set(count + 1);
    }

    public int getCount() {
        Integer integer = threadLocal.get();
        return integer != null ? integer : 0;
    }

    public static void main(String[] args) throws InterruptedException {
        SafeThread testThreadLocal = new SafeThread();
        for (int i = 0; i < 20; i++) {
            new ThreadB(i, testThreadLocal).start();
        }
        Thread.sleep(200);

        System.out.println("realCount:" + testThreadLocal.getCount());
    }

}
